package cn.king.springframework.beans.factory.support;

import cn.king.springframework.beans.BeanException;
import cn.king.springframework.beans.factory.BeanFactory;
import cn.king.springframework.beans.factory.FactoryBean;
import cn.king.springframework.beans.factory.config.BeanDefinition;
import cn.king.springframework.beans.factory.config.BeanPostProcessor;
import cn.king.springframework.beans.factory.config.ConfigurableBeanFactory;
import cn.king.springframework.util.ClassUtil;

import java.util.ArrayList;
import java.util.List;

public abstract  class AbstractBeanFactory  extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory{
    /** ClassLoader to resolve bean class names with, if necessary */
    private ClassLoader beanClassLoader = ClassUtil.getDefaultClassLoader();
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();
    @Override
    public Object getBean(String name) throws BeanException {
        return doGetBean(name,null);
    }

    @Override
    public Object getBean(String name, Object... args) {
        return doGetBean(name,args);
    }
    protected  <T> T doGetBean(final String name,final Object[] args){
        Object bean = getSingleton(name);
        if(bean != null){
            // 如果是 FactoryBean，则需要调用 FactoryBean#getObject
            return (T)getObjectForBeanInstance(bean,name);
        }
        BeanDefinition beanDefinition = getBeanDefinition(name);
        Object factoryBean = createBean(name,beanDefinition,args);
        return (T)getObjectForBeanInstance(factoryBean,name);
    }

    private Object getObjectForBeanInstance(Object beanInstance,String beanName){
        if(!(beanInstance instanceof FactoryBean)){
            return beanInstance;
        }
        Object object = getCachedObjectForFactoryBean(beanName);
        if(null == object){
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }
        return object;
    }

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }
    public ClassLoader getBeanClassLoader(){
        return this.beanClassLoader;
    }

    @Override
    public <T> T getBean(String name, Class<T> requireType) {
        return (T)getBean(name);
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeanException;

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeanException;
}
